<template>
  <div>
    <en-table-layout
        :tableData="tableData.data"
        :loading="loading"
        :selection-change="handleSelectionChange">
        <div slot="toolbar" class="inner-toolbar">
          <div class="toolbar-btns">
            <el-button  @click="dialogImport = true" type="primary">批量修改商品</el-button>
            <el-button  @click="dialogImportSku = true" type="primary">批量修改SKU</el-button>
            <el-button type="primary" icon="el-icon-download" @click="handleExportGoodsSku" style="margin-left: 5px">导出商品SKU</el-button>
            <el-button  @click="openCopyDialog" type="primary">复制商品</el-button>
            <el-button  @click="batchGoodsDeal(1)" type="primary">批量上架商品</el-button>
            <el-button  @click="batchGoodsDeal(2)" type="primary">批量下架商品</el-button>
            <el-button  @click="batchGoodsSubsidy()" type="primary">批量设置补贴</el-button>
          </div>
          <div class="toolbar-search">
            <en-table-search
              @search="searchEvent"
              @advancedSearch="advancedSearchEvent"
              advanced>
              <template slot="advanced-content">
                <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                  <el-form-item label="商品名称">
                    <el-input size="medium" v-model="advancedForm.goods_name" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="商品ID">
                    <el-input size="medium" v-model="advancedForm.goods_id" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="店铺名称">
                    <en-shop-picker @changed="(shop) => { advancedForm.seller_id = shop.shop_id }"/>
                  </el-form-item>
                  <el-form-item label="商品类别">
                    <en-category-picker @changed="categoryChanged"/>
                  </el-form-item>
                  <el-form-item label="商品品牌">
                    <en-brand-picker @changed="(brand) => { advancedForm.brand_id = brand.brand_id }"/>
                  </el-form-item>
                  <el-form-item label="价格区间">
                    <el-input size="medium" v-model="advancedForm.start_price" :maxlength="10" style="width: 100px;" clearable></el-input>
                    -
                    <el-input size="medium" v-model="advancedForm.end_price" :maxlength="10" style="width: 100px;" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="商品状态">
                    <el-select v-model="advancedForm.market_enable" placeholder="请选择" clearable>
                      <el-option label="售卖中" value="1"/>
                      <el-option label="已下架" value="0"/>
                    </el-select>
                  </el-form-item>
                </el-form>
              </template>
            </en-table-search>
          </div>
        </div>

      <template slot="table-columns">
        <el-table-column type="selection" fixed width="47"/>
        <el-table-column label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.is_auth === 1"
              size="mini"
              :type="scope.row.market_enable === 0 ? 'primary' : 'danger'"
              @click="handleOperateGoods(scope.$index, scope.row)">{{ scope.row.market_enable === 0 ? '上架' : '下架' }}</el-button>
            <el-button size="mini" @click="batchGoodsSubsidy(scope.row)">补贴</el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="120">
          <template slot-scope="scope">
            <a :href="MixinBuyerDomain + '/goods/' + scope.row.goods_id" target="_blank">
              <img :src="scope.row.thumbnail" class="goods-image"/>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="goods_id" label="商品ID" width="80"/>
        <el-table-column label="商品名称" width="250">
          <div slot-scope="scope" style="text-align: left;">
            <a :href="MixinBuyerDomain + '/goods/' + scope.row.goods_id" class="goods_name" target="_blank">
              {{ scope.row.goods_name }}
            </a>
          </div>
        </el-table-column>
        <el-table-column label="搜索优先级" min-width="110">
          <template slot-scope="scope">
            <el-rate v-model="scope.row.priority"
                    @change="handleModifyPriority(scope.row)"
                    :max="3"
                    show-text
                    :texts="['低', '中', '高']">
            </el-rate>
          </template>
        </el-table-column>
        <el-table-column prop="seller_name" label="店铺名称" min-width="150"/>
        <el-table-column label="商品价格" min-width="120">
          <template slot-scope="scope">{{ scope.row.price | unitPrice('￥') }}</template>
        </el-table-column>
        <el-table-column label="补贴比例" min-width="80">
          <template slot-scope="scope">{{ scope.row.subsidy_rate | unitSubsidyRate('%') }}</template>
        </el-table-column>
        <el-table-column label="库存" min-width="80" prop="quantity"/>
        <el-table-column label="可用库存" min-width="80" prop="enable_quantity"/>
        <el-table-column label="商品状态" min-width="80" :formatter="marketStatus"/>
      </template>
      <el-pagination
        v-if="tableData"
        slot="pagination"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="tableData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
      <!-- 导入商品 -->
      <el-dialog
        title="导入"
        class="dialog-coding-import"
        :visible.sync="dialogImport"
        width="480px">
        <el-button class="download" type="primary">
          <a href="https://egale-shop.oss-cn-hangzhou.aliyuncs.com/excel/%E5%95%86%E5%93%81_%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9.xlsx">下载模板</a>
        </el-button>
        <div class="mt10">只能上传xlsx文件，单次不超过1000条</div>
        <el-upload
          class="coding-import"
          drag
          accept=".xlsx"
          :action="actionUploadFileUrl"
          :http-request="importGoods"
          :show-file-list="false"
          :before-upload="beforeUploadFile">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>

      <!-- 导入sku -->
      <el-dialog
        title="导入"
        class="dialog-coding-import"
        :visible.sync="dialogImportSku"
        width="480px">
        <el-button class="download" type="primary">
          <a href="https://egale-shop.oss-cn-hangzhou.aliyuncs.com/excel/%E5%95%86%E5%93%81sku_%E6%89%B9%E9%87%8F%E4%BF%AE%E6%94%B9.xlsx">下载模板</a>
        </el-button>
        <div class="mt10">只能上传xlsx文件，单次不超过1000条sku</div>
        <el-upload
          class="coding-import"
          drag
          accept=".xlsx"
          :action="actionUploadSkuFileUrl"
          :http-request="importGoodsSku"
          :show-file-list="false"
          :before-upload="beforeUploadFile">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>

      <!-- 复制商品sku -->
      <el-dialog
        title="复制商品"
        class="dialog-coding-import"
        :visible.sync="dialogCopySku"
        width="480px"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form :model="copyForm" :rules="copyFormRules" ref="copyForm" label-width="110px">
          <p class="tips">
            只温馨提示：已选中{{selectedData.length}}个商品进行复制操作！
          </p>
          <el-form-item label="复制到店铺：" required>
            <en-shop-picker class="chooseCity" @changed="(shop) => { copyForm.city = shop.shop_id }"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCopySku = false">取 消</el-button>
          <el-button type="primary" @click="submitCopyForm">确定复制</el-button>
        </span>
      </el-dialog>

      <!-- 批量设置补贴 -->
      <el-dialog
        title="设置补贴"
        class="dialog-coding-import"
        :visible.sync="subsidyDialog"
        width="480px"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form :model="subsidyForm" :rules="subsidyFormRules" ref="subsidyForm" label-width="92px">
          <p class="tips" v-if="selectedData.length">
            只温馨提示：已选中{{selectedData.length}}个商品设置平台补贴！
          </p>
          <el-form-item label="补贴比例：" prop="subsidy_rate">
            <el-input size="medium" v-model="subsidyForm.subsidy_rate" clearable>
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="补贴设置：" prop="subsidy_rate">
          <el-radio-group v-model="subsidyType">
            <el-radio :label="1">参与补贴</el-radio>
            <el-radio :label="0">不参与补贴</el-radio>
          </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelSubsidyForm('subsidyForm')">取 消</el-button>
          <el-button type="primary" @click="submitSubsidyForm('subsidyForm')">确定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
  import { api } from '~/ui-domain'
  import * as API_goods from '@/api/goods'
  import { copyShopList } from '@/api/shop'
  const actionImportGoodsUrl = `${api.admin}/admin/excel/importGoods`;
  const actionImportGoodsSkuUrl = `${api.admin}/admin/excel/importGoodsSku`;

  export default {
    name: 'goodsList',
    data() {
      return {
        actionUploadFileUrl: actionImportGoodsUrl,
        actionUploadSkuFileUrl: actionImportGoodsSkuUrl,
        //导入的弹窗显示与否
        dialogImport: false,
        dialogImportSku: false,
        dialogCopySku: false,
        subsidyDialog: false, //补贴窗口
        subsidyForm: {
          subsidy_rate: undefined //补贴比例
        },
        curSubsidyItem: undefined, //当前补贴对象
        downloadName: '收入编码导入模板', // 下载导入模版名

        /** 列表loading状态 */
        loading: false,
        subsidyType: 0,

        /** 列表参数 */
        params: {
          page_no: 1,
          page_size: 10
        },

        /** 商品列表数据 */
        tableData: '',
        /** 开启的城市列表 */
        cityData: null,
        /** 被选数据 */
        selectedData: [],

        /** 高级搜索数据 */
        advancedForm: {
          goods_name: '',
          goods_sn: '',
          seller_name: '',
          category_path: ''
        },

        /** 复制商品数据 */
        copyForm: {
          city: ''
        },
        // 审核商品 表单校验
        copyFormRules: {
          city: [{ required: true, message: '请选择复制地区！', trigger: 'change' }]
        },
        // 审核商品 表单校验
        subsidyFormRules: {
          subsidy_rate: [{ required: true, message: '请输入补贴比例！', trigger: 'blur' }]
        }
      }
    },
    filters: {
      unitSubsidyRate(val, unit) {
        if (val<0) {
          return '-'
        } else {
          return (val || 0) + (unit || '')
        }
      }
    },
    mounted() {
      this.GET_GoodsList()
    },
    activated() {
      this.GET_GoodsList()
    },
    methods: {
      /** 分页大小发生改变 */
      handlePageSizeChange(size) {
        this.params.page_size = size
        this.GET_GoodsList()
      },

      /** 分页页数发生改变 */
      handlePageCurrentChange(page) {
        this.params.page_no = page
        this.GET_GoodsList()
      },

      /** 单个商品上架、下架操作确认 */
      handleOperateGoods(index, row) {
        if (row.market_enable === 0) {
          this.$confirm('确定要上架这个商品吗？', '提示', { type: 'warning' }).then(() => {
            API_goods.upGoods(row.goods_id).then(response => {
              row.market_enable = 1
              this.$message.success('上架商品成功！')
            })
          }).catch(() => {})
        } else {
          this.$prompt('请输入下架原因', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValidator: (val) => {
              if (val.length > 200) {
                return '下架原因最多200个字符'
              }
              return true
            },
            inputPattern: /.+/,
            inputErrorMessage: '请填写下架原因！'
          }).then(({ value }) => {
            API_goods.underGoods(row.goods_id, value).then(() => {
              row.market_enable = 0
              this.$message.success('下架商品成功！')
            })
          }).catch(() => {})
        }
      },

      /** 销售状态格式化 */
      marketStatus(row, column, cellValue) {
        const { market_enable, is_auth } = row
        if (is_auth === 1) {
          return row.market_enable === 1 ? '售卖中' : '已下架'
        } else {
          return is_auth === 2 ? '审核拒绝' : '待审核'
        }
      },

      /** 改变优先级 */
      handleModifyPriority(row) {
        API_goods.modifyPriority(row.goods_id, row.priority).then(_ => {
          this.loading = false
        }).catch()
      },

      /** 搜索事件触发 */
      searchEvent(data) {
        this.params = {
          ...this.params,
          keyword: data
        }
        this.params.page_no = 1
        Object.keys(this.advancedForm).forEach(key => delete this.params[key])
        this.GET_GoodsList()
      },

      /** 高级搜索事件触发 */
      advancedSearchEvent() {
        this.params = {
          ...this.params,
          ...this.advancedForm
        }
        delete this.params.keyword
        this.params.page_no = 1
        this.GET_GoodsList()
      },

      /** 高级搜索中 分类选择组件值发生改变 */
      categoryChanged(data) {
        this.advancedForm.category_path = data.category_path || ''
      },

      GET_GoodsList() {
        this.loading = true
        API_goods.getGoodsList(this.params).then(response => {
          this.loading = false
          this.tableData = response
        }).catch(() => (this.loading = false))
      },
      /**
        * @date 2020/07/20
        * @author kjh
        * @description { 上传商品}
      */
      importGoods (_content) {
        let _params = new FormData();
        _params.append('file', _content.file);

        API_goods.importGoods(_params).then(res => {
          this.$message.success('文件上传成功');
          this.dialogImport = false;
          this.GET_GoodsList();
        });
      },
      /**
        * @date 2020/07/20
        * @author kjh
        * @description {上传sku}
      */
      importGoodsSku (_content) {
        let _params = new FormData();
        _params.append('file', _content.file);

        API_goods.importGoodsSku(_params).then(res => {
          this.$message.success('文件上传成功');
          this.dialogImportSku = false;
          this.GET_GoodsList();
        });
      },
      openCopyDialog(){
        if (this.selectedData.length < 1) {
          this.$message.error('您未选中任何商品！')
        } else {
          this.dialogCopySku = true;
          this.getCityList();
        }
      },

      /** 当选择项发生变化 */
      handleSelectionChange(val) {
        this.selectedData = val.map(item => item.goods_id);
      },
      /**
        * @date 2020/11/18
        * @author luocheng
        * @description {复制商品}
      */
      submitCopyForm () {
        let params = {
          'goodsIds': this.selectedData.toString(),
          'sellerId': this.copyForm.city
        };
        API_goods.copyGoods(params).then(res => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.dialogCopySku = false;
          } else {
            this.$message.warning(res.message);
          }
        }).catch((err) => {
          this.$message.warning(err);
          // this.dialogCopySku = false;
        });
      },
      /**
        * @date 2020/11/18
        * @author luocheng
        * @description {复制商品城市列表}
      */
      getCityList () {
        const params = 'OPEN';
        copyShopList(params).then(res => {
          this.cityData = res;
        });
      },

      /** 导出商品SKU */
      handleExportGoodsSku() {
        API_goods.exportGoodsSku(this.params).then(response => {
          // 处理返回的文件流
          let blob = new Blob([response], {
            type: 'application/vnd.ms-excel;charset=utf-8'
          });
          let date = new Date().getFullYear() + '' + (new Date().getMonth() + 1) + '' + new Date().getDate();
          const fileName = date + name + '商品sku导出.xlsx';
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        })
      },
      beforeUploadFile (_content) {
        let _file = _content.name;
        let extension = _file.substring(_file.lastIndexOf('.') + 1);
        if (extension !== 'xlsx') {
          this.$message.warning('只能上传后缀为xlsx的文件');
        }
      },
      batchGoodsDeal(type) {
        this.$confirm('确定要'+ (type === 1? '上': '下') +'架这个商品吗？', '提示', { type: 'warning' }).then(() => {
          let api = type === 1 ? API_goods.batchGoodsUp : API_goods.batchGoodsUnder;
          let params = this.selectedData;
          api(params).then((res) => {
            this.$message.success(res);
            this.GET_GoodsList();
          }).catch((err) => {
            this.$message.warning(err);
          })
        })
      },
      batchGoodsSubsidy(row) {
        if (!this.selectedData.length && !row) {
          this.$message.warning('请选择要设置的商品');
          return
        }
        this.subsidyDialog = true;
        this.curSubsidyItem = row;
      },
      submitSubsidyForm(subsidyForm) {
        let goods_ids = ''
        if (this.selectedData.length) {
          goods_ids = this.selectedData.toString();
        } else {
          goods_ids = this.curSubsidyItem.goods_id
        }
        let params = {
          'subsidy_rate': this.subsidyType ? this.subsidyForm.subsidy_rate : -1
        };
        API_goods.batchEditGoods(goods_ids, params).then(res => {
          if (res) {
            this.$message.success('补贴比例设置成功！');
            this.GET_GoodsList();
            this.subsidyDialog = false;
            this.$refs[subsidyForm].resetFields();
          } else {
            this.$message.warning(res.message);
          }
        }).catch((err) => {
          this.$message.warning(err);
          // this.dialogCopySku = false;
        });
      },
      cancelSubsidyForm(subsidyForm) {
        this.$refs[subsidyForm].resetFields();
        this.subsidyDialog = false;
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  /deep/ .el-table td:not(.is-left) {
    text-align: center;
  }

  .inner-toolbar {
    display: flex;
    width: 100%;
    justify-content: space-between;
  }

  .goods-image {
    width: 50px;
    height: 50px;
  }
  .goods_name {
    color: #4183c4;
    &:hover {
      color: #f42424;
    }
  }
   .dialog-coding-import {
    .coding-import {
      padding: 20px 30px;
      text-align: center;
    }
    .download{
      position: relative;
      top: -20px;
    }
  }
  .tips{
    color: #f42424;
  }
  .chooseCity{
    width: 330px;
  }
</style>
